﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
using InstrumentCheck.Module;
using InstrumentCheck.SQLHelper;
using InstrumentCheck.BLL;


namespace InstrumentCheck.MailJob
{
    public partial class Form1 : Form
    {
        public static string Server = System.Configuration.ConfigurationSettings.AppSettings["WebIP"].ToString();
        private Boolean flag = false;
        DateTime NextTime;
        public Form1()
        {
            InitializeComponent();
        }
        protected void sendMail(string MailBody, string MailSubject, MailAddress[] MailCC, MailAddress MailTo)
        {
            MailMessage Mail = new MailMessage();
            UTF8Encoding mailEncoding = new UTF8Encoding();
            Mail.Subject = MailSubject;
            Mail.Body = MailBody;
            if (MailCC.Length > 0)
            {
                foreach (MailAddress mailcc in MailCC)
                    Mail.CC.Add(mailcc);
            }
            Mail.To.Add(MailTo);
            Mail.BodyEncoding = mailEncoding;
            Mail.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Send(Mail);
        }
        public bool checklblTime(string time)
        {
            bool Error = true;
            if (!(Regex.IsMatch(time, "^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$")))
            {
                MessageBox.Show("格式錯誤！請輸入正確的時間格式");
                Error = false;

            }
            return Error;

        }

        private void btnSend_Click(object sender, EventArgs e)
        {

            try
            {

                if (txtSettingTime.Text.Trim() != "")
                {
                    if (checklblTime(txtSettingTime.Text.Trim().ToString()) == false)
                        return;
                }
                txtSettingTime.ReadOnly = true;
                lblStatus.Text = "正在執行中......";
                insertAlertList();
                BeginSendMail();
                flag = true;
                timer1.Start();
                lblStatus.Text = "發送完成!";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string tmpTime = "";
            if (txtSettingTime.Text.Trim() != "")
                tmpTime = txtSettingTime.Text.Trim().ToString();
            else
                tmpTime = "7:30:00";

            if (flag)
                NextTime = DateTime.Parse(tmpTime).AddDays(1);
            if (DateTime.Now > NextTime)
            {
                lblStatus.Text = "正在執行中......";
                insertAlertList();
                BeginSendMail();
                flag = true;
                lblStatus.Text = "發送完成!";
            }
            else
                flag = false;
            lblCurrentTime.Text = NextTime.ToString("yyyy/MM/dd HH:mm:ss");
            lblSystemTime.Text = DateTime.Now.ToString("HH:mm:ss");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //insertAlertList();
        }
        private void insertAlertList()
        {
            List<AlertMail> alertmail = new List<AlertMail>();
            alertmail = MailJob_bll.getAlertList();
            if (alertmail.Count == 0)
                return;
            foreach (AlertMail mail in alertmail)
            {
                if (MailJob_bll.IsExist(mail.Item.AssetNO, mail.Item.NeedCorrectDate.Value, mail.Item.CorrectCycle.Value))
                    return;
                MailJob_bll.InsertAlertList(mail);
            }

        }
        private void BeginSendMail()
        {
            List<AlertMail> mailInfo = new List<AlertMail>();
            mailInfo = MailJob_bll.MailInfo();
            foreach (AlertMail mail in mailInfo)
            {
                InitMailInfo(mail);
            }

        }
        private void InitMailInfo(AlertMail alertmail)
        {
            int type = 0;
            switch (alertmail.Item.AssetType)
            {
                case AssetType.FixedAsset:
                    type = 1;
                    break;
                case AssetType.RestrictedItems:
                    type = 2;
                    break;
                default:
                    break;
            }
            //string url = "http://localhost:1199/MailApproval.aspx?fasno=" + alertmail.Item.AssetNO.ToString() + "&date=" + alertmail.Item.NeedCorrectDate.Value.ToShortDateString() + "&type=" +type;
            string url = "http://" + Server + "/MailApproval.aspx?fasno=" + alertmail.Item.AssetNO.ToString() + "&date=" + alertmail.Item.NeedCorrectDate.Value.ToShortDateString() + "&type=" + type;
            string MailSubject = "儀器校驗到期通知 :" + alertmail.Item.AssetNO + "-" + alertmail.Item.ChiName + "";
            string MailBody = "<html><body><div style=\" font-size:9pt\">主旨 = [簽核]校驗到期 :" + alertmail.Item.Keeper.EmpNO + " " + alertmail.Item.Keeper.EmpChineseName + "–";
            MailBody += alertmail.Item.AssetNO + "-" + alertmail.Item.ChiName + "- " + alertmail.Item.Spec + "<br>";
            MailBody += " 需完成校驗日期 = " + alertmail.Item.NeedCorrectDate + "<br> ";
            MailBody += " 簽核結果 = [尚未完成]";
            MailBody += " 請先填寫PR單申請校驗費用,如確定已知悉並已開始進行相關作業，請按以下link ,將會停止此warning的發送<br>";
            MailBody += " <a href=" + url + "> 確認已開始校驗作業，停止warning mail 發送</a><br></div>";
            MailBody += " <P><div>請確實執行定期送校,確保設備之精確度</div>";
            List<MailAddress> MailCC = new List<MailAddress>();
            List<User> user = new List<User>();
            user = MailJob_bll.MailCC();
            foreach (User tmpUser in user)
            {
                MailAddress ads = new MailAddress(tmpUser.Email);
                MailCC.Add(ads);
            }
            MailCC.Add(new MailAddress("YuyenTeng@aopen.com"));
            MailAddress MailTo = new MailAddress(alertmail.Item.Keeper.Email);
            sendMail(MailBody, MailSubject, MailCC.ToArray(), MailTo);

        }


    }
}
